package com.sawyerqiu.ui;

import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
import com.sawyerqiu.constant.DateConstant;
import com.sawyerqiu.constant.OrderExcelDataParseType;
import com.sawyerqiu.model.OrderExcelData;
import com.sawyerqiu.model.OrderExcelDataBuilder;
import com.sawyerqiu.model.Result;
import com.sawyerqiu.util.ExcelUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.math3.util.Pair;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : SawyerQiu
 * @date : 2024/7/30 11:08
 */
public class InputDataPanel extends JPanel {


    private JTextArea insertString;

    private String insertPath = "";
    private JLabel insertPathLabel;
    private JButton insertPathButton;

    private JButton inertButton;

    public InputDataPanel() {
        insertString = new JTextArea(10, 30);
        insertString.setToolTipText("输入数据");
        JScrollPane jScrollPane = new JScrollPane(insertString);

        insertPathLabel = new JLabel();
        insertPathLabel.setText("导入文件路径： ");
        insertPathButton = new JButton("请选择导入的xlxs文件");

        inertButton = new JButton("开始导入数据");

        //
        MainUi.addFileChooserAction(insertPathButton, file -> {
            if (!file.isFile()
                    || !file.getPath().endsWith("xlsx")) {
                return Result.valueOfFail("请选择正确的xlsx文件");
            }

            return Result.getSUCCESS();
        }, file -> {
            insertPath = file.getPath();
            insertPathLabel.setText("导入文件路径： " + file.getPath());
        });

        inertButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String text = insertString.getText();
                if (text == null || text.equals("")) {
                    JOptionPane.showMessageDialog(InputDataPanel.this,
                            "请输入数据", "warn", JOptionPane.WARNING_MESSAGE);
                } else if (insertPath.equals("")) {
                    JOptionPane.showMessageDialog(InputDataPanel.this,
                            "请选择导入的xlxs文件", "warn", JOptionPane.WARNING_MESSAGE);
                } else {
                    try {
                        insert();
                        JOptionPane.showMessageDialog(InputDataPanel.this,
                                "导入完成", "tip", JOptionPane.INFORMATION_MESSAGE);
                        insertString.setText("");

                    } catch (Exception e1) {
                        e1.printStackTrace();
                        JOptionPane.showMessageDialog(InputDataPanel.this,
                                "错误，请检查!!!" + e1.getMessage(), "error", JOptionPane.ERROR_MESSAGE);
                    }
                }

            }
        });

        //布局
        setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));

        add(jScrollPane);

        JPanel jPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        jPanel.add(insertPathLabel);
        jPanel.add(insertPathButton);

        add(jPanel);
        add(inertButton);
    }

    private void insert() throws Exception {
        String text = insertString.getText();
        text = text.replace("\n", "\",\"");
        text = text.replace("：", ":");

        java.util.List<String> strings = JSON.parseArray("[\"" + text + "\"]", String.class);
        if (strings.size() == 0) {
            throw new ParseException("没有时间", 0);
        }

        String dateStr = strings.get(0);
        Date date = DateUtils.parseDate(dateStr, DateConstant.DATE_FORMAT);

        java.util.List<Pair<OrderExcelDataParseType, java.util.List<OrderExcelDataBuilder>>> typeDatumList = parseDateBuilderThrow(strings, date);
        if (typeDatumList.isEmpty()) {
            JOptionPane.showMessageDialog(InputDataPanel.this,
                    "空数据：", "warn", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String sheetName = DateUtils.format(date, DateConstant.MONTH_DATE_FORMAT);
        fillHistoryData(sheetName, typeDatumList);

        java.util.List<OrderExcelData> collect = typeDatumList.stream().flatMap(p -> p.getSecond().stream()).map(OrderExcelDataBuilder::build).collect(Collectors.toList());
        ExcelUtil.writeAppend(insertPath, sheetName, OrderExcelData.class, collect);
    }

    private void fillHistoryData(String sheetName, java.util.List<Pair<OrderExcelDataParseType, java.util.List<OrderExcelDataBuilder>>> typeDatumList) {
        Map<String, OrderExcelDataBuilder> findHistoryBuilder = new HashMap<>();
        for (Pair<OrderExcelDataParseType, java.util.List<OrderExcelDataBuilder>> pair : typeDatumList) {
            if (pair.getFirst() != OrderExcelDataParseType.FindHistory) {
                continue;
            }

            pair.getSecond().forEach(builder -> {
                findHistoryBuilder.put(builder.getBuyer(), builder);
            });
        }

        if (MapUtils.isEmpty(findHistoryBuilder)) {
            return;
        }

        ExcelUtil.readDo(insertPath, sheetName, OrderExcelData.class, orderExcelData -> true, orderExcelData -> {
            String buyer = orderExcelData.getBuyer();

            String[] split = buyer.split("（");
            String name = split[0];

            OrderExcelDataBuilder orderExcelDataBuilder = findHistoryBuilder.remove(name);
            if (orderExcelDataBuilder != null) {
                orderExcelDataBuilder.setBuyer(orderExcelData.getBuyer());
            }
        });

        if (MapUtils.isEmpty(findHistoryBuilder)) {
            return;
        }

        for (Pair<OrderExcelDataParseType, java.util.List<OrderExcelDataBuilder>> pair : typeDatumList) {
            if (pair.getFirst() == OrderExcelDataParseType.FindHistory) {
                continue;
            }

            for (OrderExcelDataBuilder template : pair.getSecond()) {
                String buyer = template.getBuyer();

                String[] split = buyer.split("（");
                String name = split[0];

                OrderExcelDataBuilder orderExcelDataBuilder = findHistoryBuilder.remove(name);
                if (orderExcelDataBuilder != null) {
                    orderExcelDataBuilder.setBuyer(template.getBuyer());
                }
            }

        }

    }

    private java.util.List<Pair<OrderExcelDataParseType, java.util.List<OrderExcelDataBuilder>>> parseDateBuilderThrow(java.util.List<String> strings, Date date) throws Exception {
        java.util.List<Pair<OrderExcelDataParseType, java.util.List<OrderExcelDataBuilder>>> typeDatumList = new ArrayList<>();

        int temp = 1;
        while (temp < strings.size()) {
            if (strings.get(temp).equals("")) {
                temp += 1;
                continue;
            }

            checkSize(strings, temp + 1);

            String param = strings.get(temp + 1);

            OrderExcelDataParseType type;
            if (param.contains("斤")) {
                type = OrderExcelDataParseType.FindHistory;
            } else {
                type = OrderExcelDataParseType.Normal;
            }

            Pair<Integer, java.util.List<OrderExcelDataBuilder>> parse = type.parse(date, strings, temp);

            temp = parse.getFirst();
            java.util.List<OrderExcelDataBuilder> second = parse.getSecond();

            if (!CollectionUtils.isEmpty(second)) {
                typeDatumList.add(Pair.create(type, second));
            }
        }

        return typeDatumList;
    }

    private void checkSize(List<String> strings, int temp) {
        if (temp >= strings.size()) {
            throw new IllegalStateException();
        }
    }
}
